/*
 * Copyright (c) 2013-2015 SimaStudio. All rights reserved.
 *
 * This software is the confidential and proprietary information of SimaStudio.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with SimaStudio.
 *
 * SimaStudio MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * SimaStudio SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package com.asiainfo.integration.xml;

import com.asiainfo.integration.utils.ConfigProvider;
import org.codehaus.stax2.XMLInputFactory2;
import org.codehaus.stax2.XMLStreamReader2;
import org.codehaus.stax2.evt.XMLEvent2;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

/**
 * Usage:
 *
 * @author Charkey
 * @date 4/24/2016
 */
@SuppressWarnings("Since15")
public class XmlSAXTester {

    public static void main(String[] args) {
        try {
            URL url = ConfigProvider.class.getClassLoader().getResource("config/task/createServiceOrder-1000042367-NO000004MCNA.xml");
            InputStream in = new FileInputStream(new File(url.toURI().getPath()));
            XMLInputFactory2 parser = (XMLInputFactory2) XMLInputFactory2.newInstance();
            parser.setProperty(XMLInputFactory2.IS_REPLACING_ENTITY_REFERENCES, Boolean.FALSE);
            parser.setProperty(XMLInputFactory2.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
            parser.setProperty(XMLInputFactory2.IS_COALESCING, Boolean.FALSE);
            parser.configureForLowMemUsage();
            XMLStreamReader2 reader = (XMLStreamReader2) parser.createXMLStreamReader(in);
            boolean flag = false;  // 跳出读取循环
            int event = reader.getEventType(); //获取解析事件类型
            while (reader.hasNext()) {
                if (flag) {
                    break;
                }
                event = reader.next();
                switch (event) {
                    case XMLEvent2.START_ELEMENT: //开始标签事件 1
                        System.out.println("reader.getLocalName():" + reader.getLocalName());
                        break;
                    case XMLEvent2.CHARACTERS:    //标签内容事件 4
                        System.out.println("Value:" + reader.getText() + ":End"); //获取标签值
                        break;
                    case XMLEvent2.END_ELEMENT:   //结束标签动作 2
                        break;
                }
            }
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}